//
//  LeaderAuditController.m
//  Estate
//
//  Created by heyong on 16/9/8.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "TableTopStateCell.h"
#import "H1_ImagesCell.h"
#import "LeaderAuditController.h"
#import "DefaineCell.h"
#import "selectBtnCell.h"
#import "PositionTableCell.h"
#import "B_wuLiaoCell.h"
#import "QianDTableCell.h"
#import "OrientationViewController.h"
#import "ScoureCell.h"
#import "AttachmentPhotoCell.h"
#import "FDAlertView.h"
#import "AlertVIew.h"
#import "doubleFileTableCell.h"
#import "DBYSDetailViewController.h"

@interface LeaderAuditController (){
    FDAlertView *alert;
    UIButton *btn_1,*btn_2;
    int check;
    FMDatabase *_db;
    //存储审核信息
    NSString *_recificateReview;
    //督办id
    NSString *_dubanId;
}
@property (strong, nonatomic) Tweet *curTweet;

@end

@implementation LeaderAuditController
-(TPKeyboardAvoidingTableView *)tableView{
    if(_tableView==nil){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:self.view.bounds];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        [_tableView registerClass:[selectBtnCell class] forCellReuseIdentifier:@"sCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defaine"];
        [_tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
        [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
        [_tableView registerNib:[UINib nibWithNibName:@"ScoureCell" bundle:nil] forCellReuseIdentifier:@"scoureCell"];
        
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (NSMutableDictionary *)dataDic{
    if(!_dataDic){
        _dataDic=[NSMutableDictionary dictionary];
    }
    return _dataDic;
}
- (NSMutableArray *)leftImageArr{
    if(!_leftImageArr){
        _leftImageArr=[NSMutableArray array];
    }
    return _leftImageArr;
}
- (NSMutableArray *)rightImageArr{
    if(!_rightImageArr){
        _rightImageArr=[NSMutableArray array];
    }
    return _rightImageArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"检查任务单";
    //添加提交按钮
    if(self.isEdit){
        [self cteateRightItem];
    }
    self.view.backgroundColor=[UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
    [self.view addSubview:self.tableView];
  
    _db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [self setData];
}

#pragma mark-设置数据
- (void)setData{
    if(self.recordId){
        [_db open];
        //巡检流程记录
//        NSString *sql_1= [NSString stringWithFormat:@"select * from INSPECT_PROCESS_RECORD where INSPECT_USER_ITEM_ID =(select INSPECT_USER_ITEM_ID from INSPECT_PROCESS_RECORD where ID='%@') and inspect_item_state='4' order by(create_time)desc limit 0,1",self.recordId];
        NSString *sql_1=@"";
        if([self.flag isEqualToString:@"query"]){
            sql_1= [NSString stringWithFormat:@"select * from INSPECT_PROCESS_RECORD where INSPECT_USER_ITEM_ID =(select INSPECT_USER_ITEM_ID from INSPECT_PROCESS_RECORD where ID='%@') order by(create_time)desc limit 0,1",self.recordId];
        }else{
            sql_1= [NSString stringWithFormat:@"select * from INSPECT_PROCESS_RECORD where INSPECT_USER_ITEM_ID =(select INSPECT_USER_ITEM_ID from INSPECT_PROCESS_RECORD where ID='%@') and inspect_item_state='4' order by(create_time)desc limit 0,1",self.recordId];
        }
        
 
        FMResultSet *result_1=[_db executeQuery:sql_1];
        while ([result_1 next]) {
            NSDictionary *dic=[result_1 resultDictionary];
            self.dataDic=[NSMutableDictionary dictionaryWithDictionary:dic];
        }
        if(!self.dataDic){
            NSLog(@"self.dataDic为nil");
        }else{
            // 添加跳转按钮
            _dubanId=[LSUtility queryInspectSuperProcessId: [self.dataDic objectForKey:@"INSPECT_ITEM_ID"]];
            if(![_dubanId isEqualToString:@""]){
                self.jumpBtn=[[UIButton alloc]initWithFrame:CGRECTS(280, 300, 100, 100)];
                [_jumpBtn setImage:[UIImage imageNamed:@"yijianbtn"] forState:UIControlStateNormal];
                [self.view addSubview:_jumpBtn];
                [_jumpBtn addTarget:self action:@selector(JumpVC) forControlEvents:UIControlEventTouchUpInside];
            }
        }
        //例行巡检
        if(![self.ipqc isEqualToString:@"extra"]){
            //查询父级类
            NSString *sql_2=[NSString stringWithFormat:@"select * from INSPECT_ITEM where id in (select PARENT_ID from INSPECT_ITEM where id in (select INSPECT_ITEM_ID from INSPECT_PROCESS_RECORD where id='%@'))",self.recordId];
        
            FMResultSet *result_2=[_db executeQuery:sql_2];
            while ([result_2 next]) {
                NSString *grop=[result_2 stringForColumn:@"INSPECT_NAME"];
                [self.dataDic setObject:grop forKey:@"class"];
            }
            //查询巡检项
            NSString *sql_3= [NSString stringWithFormat:@"select inspect_name from INSPECT_ITEM where id in (select INSPECT_ITEM_ID from INSPECT_PROCESS_RECORD where id='%@')",self.recordId];
            FMResultSet *result_3=[_db executeQuery:sql_3];
            while ([result_3 next]) {
                NSString *itemName=[result_3 stringForColumn:@"inspect_name"];
                [self.dataDic setObject:itemName forKey:@"itemName"];
            }
        }else{
            //用户巡检项关联ID INSPECT_USER_ITEM_ID
            NSString *user_item_id=self.dataDic[@"INSPECT_USER_ITEM_ID"];
            NSString *sql_2= [NSString stringWithFormat:@"select INSPECT_ADDTIONAL_NAME from INSPECT_USER_ITEM where id='%@'",user_item_id];
            FMResultSet *result_2=[_db executeQuery:sql_2];
            while ([result_2 next]) {
                NSString *itemName=[result_2 stringForColumn:@"INSPECT_ADDTIONAL_NAME"];
                [self.dataDic setObject:itemName forKey:@"itemName"];
            }
        }
        //查询整改前附件
        NSString *fileId=[LSUtility queryInspectStateId:self.recordId state:@"2"];
        
        NSArray *fileArray=[LSUtility queryAllAttachment:fileId];
        for (NSDictionary *fileDic in fileArray) {
            NSString *fileName=fileDic[@"FILE_NAME"];
            NSString *filePath=[DEF_FILE_PATH stringByAppendingString:
                                [NSString stringWithFormat:@"/%@",fileName]];
            [self.leftImageArr addObject:filePath];
        }
        
//        通过userItemId查询整改后附件
        //整改后的附件
        NSString *fileId_2=[LSUtility queryInspectStateId:self.recordId state:@"4"];
        NSArray *fileArray_2=[LSUtility queryAllAttachment:fileId_2];
        for (NSDictionary *fileDic in fileArray_2) {
            NSString *fileName=fileDic[@"FILE_NAME"];
            NSString *filePath=[DEF_FILE_PATH stringByAppendingString:
                                [NSString stringWithFormat:@"/%@",fileName]];
            [self.rightImageArr addObject:filePath];
        }
        [_db close];
    }
    
 
}

#pragma mark -保存
- (void)clickSave{
    
    NSString *state4Id=[LSUtility queryInspectStateId:_recordId state:@"4"];
    
    //流程记录表插入
    NSMutableDictionary *_tempDic=[LSUtility queryInspectRecordById:state4Id];
    
    NSString *item_state=@"";
    if(check==1){
        item_state=@"5";
    }else if (check==2){
        item_state=@"3";
    }
    NSDictionary *dic=@{
                        @"ID":[NSUUID UUID].UUIDString,
                        @"INSPECT_ITEM_STATE":item_state,
                        @"CREATE_USER_NAME":USERID,
                        @"CREATE_TIME":[LSUtility nowTime],
                        @"CREATE_IP":[LSUtility getIPAddress],
                        @"LOCAL_MODIFY_STATE":@"ADD",
                        };
    DBHelper *helper=[DBHelper help];
    [_tempDic setValuesForKeysWithDictionary:dic];
    [helper DataBase:_db insertKeyValues:_tempDic intoTable:INSPECT_PROCESS_RECORD];

    //修改用户巡检项表
    NSString *usetItemId=_tempDic[@"INSPECT_USER_ITEM_ID"];
    if(check==1){
        [LSUtility updateInspectUserItembyId:usetItemId andState:5];
    }else  if(check==2){
        [LSUtility updateInspectUserItembyId:usetItemId andState:3];
    }    
    
    //修改任务表为待整改
    
    NSNotification * notice = [NSNotification notificationWithName:@"Refresh_xjhbym" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark- 弹出框
//创建右上角审阅按钮
- (void)cteateRightItem{
    
    btn_1=[[UIButton alloc]initWithFrame:CGRECTS(0, 0, 40, 20)];
    btn_1.backgroundColor=[UIColor whiteColor];
    [btn_1 setTitle:@"通过" forState:UIControlStateNormal];
    btn_1.layer.cornerRadius=3.;
    btn_1.tag=100;
    btn_1.titleLabel.font=[UIFont systemFontOfSize:11.];
    [btn_1 setTitleColor:[UIColor colorWithRed:0.29 green:0.68 blue:0.64 alpha:1.00] forState:UIControlStateNormal];
    [btn_1 addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    btn_2=[[UIButton alloc]initWithFrame:CGRECTS(0, 0, 40, 20)];
    btn_2.tag=101;
    btn_2.backgroundColor=[UIColor whiteColor];
    btn_2.titleLabel.font=[UIFont systemFontOfSize:11.];
    btn_2.layer.cornerRadius=3.;
    [btn_2 setTitle:@"不通过" forState:UIControlStateNormal];
    [btn_2 setTitleColor:[UIColor colorWithRed:0.75 green:0.19 blue:0.23 alpha:1.00] forState:UIControlStateNormal];
    [btn_2 addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *bar_Btn_1=[[UIBarButtonItem alloc]initWithCustomView:btn_1];
    UIBarButtonItem *bar_Btn_2=[[UIBarButtonItem alloc]initWithCustomView:btn_2];
    
    self.navigationItem.rightBarButtonItems=@[bar_Btn_2,bar_Btn_1];
}


#pragma mark -methlod
- (void)clickAction:(UIButton *)sender{
    if(sender.tag==100){
        //合格
        [self showAlert];
        check=1;
        btn_1.hidden=YES;
        btn_2.hidden=YES;
        
    } else if(sender.tag==101){
        //不合格
        [self showAlert];
        check=2;
        btn_1.hidden=YES;
        btn_2.hidden=YES;
        
    } else if(sender.tag==102){
        //提交
        if(!_recificateReview){
            [LSUtility showToastWithMessage:@"请输入审核信息" inView:self.view Andtime:1.];
        }else{
            [self clickSave];
            [alert hide];
        }
        btn_1.hidden=NO;
        btn_2.hidden=NO;
    } else{
        //关闭审阅
        [alert hide];
        btn_1.hidden=NO;
        btn_2.hidden=NO;
    }
}

- (void)showAlert{
    
    alert = [[FDAlertView alloc] init];
    AlertVIew *contentView=[[AlertVIew alloc]initWithFrame:CGRECTS(0, 0, 300, 200)];
    
    contentView.textViewBlock=^(NSString *value){
        _recificateReview=value;
    };
    
    //提交btn
    UIButton *submitBtn= contentView.submit;
    submitBtn.tag=102;
    [submitBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //关闭btn
    UIButton *closeBtn= contentView.closeBtn;
    closeBtn.tag=103;
    [closeBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    //添加到alert
    alert.contentView = contentView;
    
    [alert show:self.view];
}

#pragma mark - 跳转
- (void)JumpVC{
    DBYSDetailViewController *GJDetail=[[DBYSDetailViewController alloc]init];
    //根据id 查询最后修改时间
    NSDictionary *dic=[self modifyForId:_dubanId];
    NSString *extend=dic[@"ADDRES_INFO"];
    NSString *beginTime=dic[@"BEGIN_TIME"];
//    NSString *endTime=dic[@"END_TIME"];
    
    GJDetail.processId =_dubanId;
    GJDetail.addresInfo = extend;
    GJDetail.beginTime = beginTime;
    [self.navigationController pushViewController:GJDetail animated:YES];
    
}

#pragma  mrak--UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
    if(section==0){
        if(row==0){
            return 40;
        }
        return 44;
    }else if(section==1){
        if(row==0||row==3||row==5){
            return 44;
        }else{
            return 120;
        }
    }else if(section==2){
        return 120;
    }else {
        if(self.leftImageArr==nil|| self.rightImageArr==nil){
            return 80*BIZ;
        }
        if(self.leftImageArr.count>self.rightImageArr.count){
            return self.leftImageArr.count *100+100;
        }else{
            return self.rightImageArr.count *100+100;
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 0.001;
    }else{
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return 4;
    }else if (section==1){
        return 6;
    }else{
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    long section=indexPath.section;
    long row=indexPath.row;

    if(section==0){
        
        if(row==0){
            
            TableTopStateCell *cell=[tableView dequeueReusableCellWithIdentifier:@"topCell" forIndexPath:indexPath];
            
            cell.title.text=[NSString stringWithFormat:@"%@  检查任务单",@""];
            
            return cell;
            
        }else if(row==1){
            
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            NSString *proName=[LSUtility getProjectNameByProjectId:self.dataDic[@"PRO_ID"]][@"PROJECT_NAME"];
            [cell setTitle:@"项   目:" andDetail:proName andLeftConstraint:20.];
            return  cell;
            
        }else if(row==2){
            
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            NSString *userId=self.dataDic[@"INSPECT_USER_ID"];
            NSString *name=[LSUtility getuserIdByUserName:userId][@"REAL_NAME"];
            [cell setTitle:@"记录人:" andDetail:name andLeftConstraint:20.];
            return  cell;
            
            
        }else{
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            NSString *time=self.dataDic[@"CREATE_TIME"];

            [cell setTitle:@"时   间:" andDetail:time andLeftConstraint:20.];
            
            return  cell;
            
        }
    }else if (section==1){
        
        if(row==0){
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            if([self.ipqc isEqualToString:@"extra"]){
                [cell setTitle:@"检 查 类:" andDetail:@"额外巡检" andLeftConstraint:20.];
            }else{
                [cell setTitle:@"检 查 类:" andDetail:self.dataDic[@"class"] andLeftConstraint:20.];
            }
            return  cell;
            
            
        }else if(row==1){
            B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            cell.textValueChangedBlock=^(NSString *value){
                
            };
            
            [cell setTitle:@"检查内容:" andPlaceHolder:@"请输入检查内容" andTextValue:self.dataDic[@"itemName"]];
            
            cell.isEdit=weakSelf.isEdit;
            
            return cell;
            
        }else if(row==2){
            
            B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            cell.isEdit=NO;
            cell.textValueChangedBlock=^(NSString *value){
            };
            
            [cell setTitle:@"检查情况:" andPlaceHolder:@"请输入检查情况" andTextValue:self.dataDic[@"INSPECT_INFO"]];
            
            return cell;
        }else if(row==3){
            selectBtnCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sCell" forIndexPath:indexPath];
            cell.isEdit=NO;
            [cell setTitle:@"结论:" andBtn_1:@"合格" andBtn_2:@"不合格" andBtn_3:@"不涉及"];
            
            NSString *state=self.dataDic[@"INSPECT_RESULT"];
            [cell InspSetBtnType:state];
            
            return cell;
            
        }else if(row==4){
            B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            
            [cell setTitle:@"备   注:" andPlaceHolder:@"请输入备注" andTextValue:self.dataDic[@"INSPECT_DESC"]];
            
            cell.isEdit=NO;
            
            return cell;
            
        }else{
            ScoureCell *cell=[tableView dequeueReusableCellWithIdentifier:@"scoureCell" forIndexPath:indexPath];
            
            cell.textFile.text=self.dataDic[@"INSPECT_SCORE"];
            cell.isEdit=NO;
            cell.textBlock=^(NSString *value){
            };
            
            return cell;
        }
    }else if (section==2){
        B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
        
        cell.textValueChangedBlock=^(NSString *value){
        };
        
        [cell setTitle:@"整改说明:" andPlaceHolder:@"" andTextValue:self.dataDic[@"INSPECT_RECIFICATE_DESC"]];
        cell.isEdit=NO;
        
        return cell;
        
    }else{
        
        doubleFileTableCell *cell=[doubleFileTableCell cellWithTableView:tableView];
        [cell setLeftImageArr:self.leftImageArr andRightImageArr:self.rightImageArr];
        return cell;
    }
}

- (NSDictionary *)modifyForId:(NSString *)ids{
    
    DBHelper *helpers=[DBHelper help];
    
    NSArray *dicArr= [helpers DataBase:_db selectKeyTypes:@{@"MODIFY_TIME":@"text",@"ADDRES_INFO":@"text",@"EXTEND_INFO":@"text",@"END_TIME":@"text",@"BEGIN_TIME":@"text"} fromTable:PROCESS whereCondition:@{@"ID":ids}] ;
    
    return  [dicArr firstObject];
}

#pragma mark scrollview
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}

@end
